package com.whc.goods.controller;


import com.whc.api.dto.GoodsCreateDto;
import com.whc.api.dto.OrderDto;
import com.whc.common.constant.RedisHeader;
import com.whc.common.context.BaseContext;
import com.whc.common.domain.Result;
import com.whc.goods.domain.dto.GoodsRequestDto;
import com.whc.goods.domain.dto.GoodsUpdateDto;
import com.whc.goods.domain.entity.Goods;
import com.whc.goods.domain.vo.GoodsVo;
import com.whc.goods.service.GoodsService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.data.redis.core.RedisTemplate;
//import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;


@RestController
@RequestMapping("/client/goods")
@Slf4j
@Api(tags = "商品接口")
public class GoodsController {

    @Autowired
    private GoodsService goodsService;
    @Resource
    private RedisTemplate<String,Object> redisTemplate;

    @ApiOperation("添加商品到购物车")
    @PostMapping("/addGoodsToCart")
    public Result addGoodsToCart(@RequestParam("goodsId")Long goodsId){
        Long currentId = BaseContext.getCurrentId();
        if(currentId==null){
            return Result.error("用户未登录");
        }
        Goods goods = goodsService.selectGoodsInCart(currentId, goodsId);
        if(goods!=null){
            return Result.error("该商品已添加");
        }
        goodsService.addGoodsToCart(currentId,goodsId);
        return Result.success();
    }

    @ApiOperation("从购物车移除多个商品")
    @PostMapping("/deleteMany")
    public Result deleteMany(@RequestParam("ids") List<Long> ids){
        Long currentId = BaseContext.getCurrentId();
        if(currentId==null){
            return Result.error("用户未登录");
        }
        goodsService.deleteMany(currentId, ids);
        return Result.success();
    }

    @ApiOperation("清空购物车")
    @PostMapping("/deleteClearCart")
    public Result deleteAll(){
        Long currentId = BaseContext.getCurrentId();
        if(currentId==null){
            return Result.error("用户未登录");
        }
        goodsService.deleteAll(currentId);
        return Result.success();
    }

    @ApiOperation("查询购物车列表")
    @GetMapping("/selectCartList")
    public Result<List<GoodsVo>> selectCartList(){
        Long currentId = BaseContext.getCurrentId();
        if(currentId==null){
            return Result.error("用户未登录");
        }
        List<GoodsVo> goodsVos = goodsService.selectCartList(currentId);
        return Result.success(goodsVos);
    }

    @ApiOperation("查询商品根据多个id")
    @GetMapping("/selectByIds")
    public Result<List<GoodsCreateDto>> selectByIds(@RequestParam("ids") List<Long> ids){
        List<GoodsCreateDto> goods = goodsService.selectByIds(ids);
        return Result.success(goods);
    }

    @ApiOperation("减库存")
    @PutMapping("/deductGoodsByIds")
    public Result deductGoodsByIds(@RequestBody OrderDto orderDto){
        goodsService.deductGoodsByIds(orderDto);
        return Result.success();
    }

    @ApiOperation("恢复库存")
    @PostMapping("/resetGoodsByIds")
    public Result resetGoodsByIds(@RequestBody OrderDto orderDto){
        goodsService.resetGoodsByIds(orderDto);
        return Result.success();
    }

    @ApiOperation("增加商品的想要数")
    @PutMapping("/addGoodWanters/{goodId}")
    public Result addGoodWanters(@PathVariable("goodId") Long goodId){
        goodsService.addGoodsWanters(goodId);
        return Result.success();
    }


    @ApiOperation("查询某用户的降价商品")
    @GetMapping("/getCheaperGoods/{userId}")
    public Result<List<GoodsVo>> getCheaperGoods(@PathVariable("userId") Long userId){
        if(redisTemplate.hasKey(RedisHeader.goodsHeaderName+"getCheaperGoods"+userId)){
            return Result.success((List<GoodsVo>)redisTemplate.opsForValue().get(RedisHeader.goodsHeaderName+"getCheaperGoods"+userId));
        }
        List<GoodsVo> goodsVos=goodsService.getCheaperGoods(userId);
        redisTemplate.opsForValue().set(RedisHeader.goodsHeaderName+"getCheaperGoods"+userId,goodsVos);
        return Result.success(goodsVos);
    }

    @ApiOperation("查询某用户的有效商品")
    @GetMapping("/getWorksGoods/{userId}")
    public Result<List<GoodsVo>> getWorksGoods(@PathVariable("userId") Long userId){
        Object o = redisTemplate.opsForValue().get(RedisHeader.goodsHeaderName + "getWorksGoods" + userId);

        if(redisTemplate.hasKey(RedisHeader.goodsHeaderName+"getWorksGoods"+userId)){
            return Result.success((List<GoodsVo>)redisTemplate.opsForValue().get(RedisHeader.goodsHeaderName+"getWorksGoods"+userId));
        }
            List<GoodsVo> goodsVos=goodsService.getWorksGoods(userId);
            redisTemplate.opsForValue().set(RedisHeader.goodsHeaderName+"getWorksGoods"+userId,goodsVos);
        return Result.success(goodsVos);
    }

    @ApiOperation("查询某用户的无效商品")
    @GetMapping("/getUnworksGoods/{userId}")
    public Result<List<GoodsVo>> getUnworksGoods(@PathVariable("userId") Long userId){
        if(redisTemplate.hasKey(RedisHeader.goodsHeaderName+"getUnworksGoods"+userId)){
            return Result.success((List<GoodsVo>)redisTemplate.opsForValue().get(RedisHeader.goodsHeaderName+"getUnworksGoods"+userId));
        }
        List<GoodsVo> goodsVos=goodsService.getUnworksGoods(userId);
        redisTemplate.opsForValue().set(RedisHeader.goodsHeaderName+"getUnworksGoods"+userId,goodsVos);
        return Result.success(goodsVos);
    }

    @ApiOperation("查询商品根据分类名")
    @GetMapping("/getListByType")
    public Result<List<GoodsVo>> getlistByType(@RequestParam("CategoryName") String CategoryName){
        if(redisTemplate.hasKey(RedisHeader.goodsHeaderName+"getListByType"+CategoryName)){
            return Result.success((List<GoodsVo>)redisTemplate.opsForValue().get(RedisHeader.goodsHeaderName+"getListByType"+CategoryName));
        }
        List<GoodsVo> goodsVos = goodsService.SelectGoodsByType(CategoryName);
        redisTemplate.opsForValue().set(RedisHeader.goodsHeaderName+"getListByType"+CategoryName,goodsVos);
        return Result.success(goodsVos);
    }

    @ApiOperation("查询商品根据分类名")
    @GetMapping("/getListByTypetExcept")
    public Result<List<GoodsVo>> getlistByType(@RequestParam("CategoryName") String CategoryName,@RequestParam("id") Long id){
//        if(redisTemplate.hasKey(RedisHeader.goodsHeaderName+"getListByType"+CategoryName)){
//            return Result.success((List<GoodsVo>)redisTemplate.opsForValue().get(RedisHeader.goodsHeaderName+"getListByType"+CategoryName));
//        }
        List<GoodsVo> goodsVos = goodsService.SelectGoodsByTypeExcept(CategoryName,id);
//        redisTemplate.opsForValue().set(RedisHeader.goodsHeaderName+"getListByType"+CategoryName,goodsVos);
        return Result.success(goodsVos);
    }

    @ApiOperation("查询所有商品")
    @GetMapping("/getAll")
    public Result<List<GoodsVo>> getAll(){
        if(redisTemplate.hasKey(RedisHeader.goodsHeaderName+"getAll")){
            System.out.println("在redis中拿到了数据："+(List<GoodsVo>)redisTemplate.opsForValue().get(RedisHeader.goodsHeaderName+"getAll"));
            return Result.success((List<GoodsVo>)redisTemplate.opsForValue().get(RedisHeader.goodsHeaderName+"getAll"));
        }
        List<GoodsVo> goodsVos=goodsService.selectAll();
        System.out.println("在mysql中拿到了数据："+goodsVos);
        redisTemplate.opsForValue().set(RedisHeader.goodsHeaderName+"getAll",goodsVos);
        return Result.success(goodsVos);
    }

    @ApiOperation("查询所有商品")
    @GetMapping("/getAllExcept/{id}")
    public Result<List<GoodsVo>> getAll(@PathVariable("id") Long id){
        if(redisTemplate.hasKey(RedisHeader.goodsHeaderName+"getAllExcept"+id)){

            return Result.success((List<GoodsVo>)redisTemplate.opsForValue().get(RedisHeader.goodsHeaderName+"getAllExcept"+id));
        }
        List<GoodsVo> goodsVos=goodsService.getAllExcept(id);
        redisTemplate.opsForValue().set(RedisHeader.goodsHeaderName+"getAllExcept"+id,goodsVos);
        return Result.success(goodsVos);
    }

    @ApiOperation("查询商品根据用户id")
    @GetMapping("/getGoodsByUserId/{id}")
    public Result<List<GoodsVo>> getGoodsByUserId(@PathVariable("id") Long id){
        List<GoodsVo> goods=goodsService.getGoodsByUserId(id);
        return Result.success(goods);
    }

    @ApiOperation("添加商品")
    @PostMapping("/addGoods")
    public Result addGoods(@RequestBody GoodsRequestDto goodsRequestDto){
        cleanCache("goods*");
        GoodsCreateDto goodsCreateDto=goodsRequestDto.getGoodsCreateDto();
        List<String>urls=goodsRequestDto.getUrls();
        long gid=goodsService.insertGoods(goodsCreateDto);
        goodsService.addGoodsPhotos(urls,gid);
        return Result.success();
    }

    @ApiOperation("根据名称查询商品")
    @GetMapping("/getOneByName")
    public Result<List<GoodsVo>> selectGoodById(@RequestParam("goodsName") String goodsName){
        List<GoodsVo> goods = goodsService.selectByName(goodsName);
        return Result.success(goods);
    }

    @ApiOperation("根据id查询商品")
    @GetMapping("/getOne")
    public Result<GoodsVo> selectGoodById(@RequestParam("id") Long id){
        GoodsVo goods = goodsService.selectById(id);
        return Result.success(goods);
    }

    @ApiOperation("根据商品id查询商品首图片")
    @GetMapping("/findBigPhoto")
    public Result<String> findBigPhoto(@RequestParam("goodId") Long goodId){
        if(redisTemplate.hasKey(RedisHeader.goodsPhoto + goodId)){
            return Result.success(((List<String>) redisTemplate.opsForValue().get(RedisHeader.goodsPhoto + goodId)).get(0));
        }
        List<String> photos = goodsService.findPhotosById(goodId);
        redisTemplate.opsForValue().set(RedisHeader.goodsPhoto+goodId,photos.get(0));
        return Result.success(photos.get(0));
    }

    @ApiOperation("根据商品id查询商品所有图片")
    @GetMapping("/findBigPhotos")
    public Result<List<String>> findBigPhotos(@RequestParam("goodId") Long goodId){
        if(redisTemplate.hasKey(RedisHeader.goodsPhoto + goodId)){
            return Result.success((List<String>) redisTemplate.opsForValue().get(RedisHeader.goodsPhoto + goodId));
        }
        List<String> photos = goodsService.findPhotosById(goodId);
        redisTemplate.opsForValue().set(RedisHeader.goodsPhoto+goodId,photos);

        return Result.success(photos);
    }

    @ApiOperation("修改商品")
    @PostMapping("/update")
    public Result selectGoodById(@RequestBody GoodsUpdateDto goodsUpdateDto){
        cleanCache("goods*");
        cleanCache("goodsPhoto*");
        goodsService.updateGoods(goodsUpdateDto);
        return Result.success();
    }

    @ApiOperation("删除商品")
    @DeleteMapping("/{gid}")
    public Result deleteGoods(@PathVariable("gid") String gid){
        cleanCache("goods*");
        cleanCache("goodsPhoto*");
        goodsService.deleteGoods(Long.parseLong(gid));
        return Result.success();
    }

    private void cleanCache(String pattern){
        Set<String> keys = redisTemplate.keys(pattern);
        System.out.println(keys);
        if(keys==null||keys.size()==0)return;
        redisTemplate.delete(keys);
        log.info("清除了相应的key");
    }
}
